<?php
class Customer_UsersController extends Zend_Controller_Action
{
	protected $_session;	
    private function _getCustomerNS()
    {
		if($this->_session == null) {
			$this->_session = new Zend_Session_Namespace('Customer');
		}
		return $this->_session;
    }
	
	public function init()
	{

	}
	
	public function indexAction()
	{

	}

	public function logoutAction()
	{
		// after log out, redirect to homepage regardless of what role the user has.
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
		$this->_getCustomerNS()->unsetAll();
		return $this->_redirect('/');
	}
	
	public function loginAction()
	{				
		$userForm = new Customer_Form_UserLogin();
		$userForm->setMethod('post')->setAction('/users/login');

		if($this->_request->isPost()) {
			if($userForm->isValid($_POST)) {
				$userData = $userForm->getValues();
				
				//////////////////////// Authentication /////////////////////////				
				$adapter = new TBB_Auth_Adapter2($userData['username'], $userData['password']);	
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($adapter);
				if($result->getCode() == Zend_Auth_Result::SUCCESS) {				 
					// redirect to module customer regardless of what role the user has					
					return $this->_redirect('/');
				} else { // when login fails
					$this->view->error = true;					
					$this->view->loginMessage = "Xin lỗi. Tên đăng nhập hoặc mật khẩu không đúng.";					
				}
				/////////////////////////////////////////////////////////////////
			} else { // when POST data is invalid, this case happens when any of fields in form is empty or invalid.
				$this->view->error = true;				
			}
		}
		
		$this->view->moduleName = $this->_request->getModuleName();			
		$this->view->form = $userForm;
	}
	
	public function registerAction()
	{
		$registerForm = new Customer_Form_UserRegister();
		if($this->_request->isPost()) {
			if($registerForm->isValid($_POST)) {
				$data = $registerForm->getValues();
				$userModel = new Customer_Model_Users();
				try {
					$userModel->registerUserAccount($data['username'], 
												$data['password'],
												$data['fullName'],
												$data['email'],
												$data['ssn'],
												$data['mobile']);					
					return $this->_redirect('/users/register-completed');
				} catch(Exception $e) {
					return TBB_Utility_Redirector::redirect('Không thể đăng ký tài khoản vì một lỗi nào đó.', 'customer', 'error', 'fatal-error');
				}			
			}
		}
		$this->view->form = $registerForm;
	}
	
	public function registerCompletedAction()
	{
		
	}

	
	


	

}